package com.cskaoyan.market.admin.controller;


import com.cskaoyan.market.admin.service.AdminOrderService;
import com.cskaoyan.market.db.domain.MarketOrder;
import com.cskaoyan.market.db.vo.MarketChannelVo;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.util.ZhouWenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {
    // 获取对应Service层对象
    @Autowired
    AdminOrderService adminOrderService;

    @GetMapping("/channel")
    private void channel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<MarketChannelVo> channelVoList = adminOrderService.channel();
        Object o = ResponseUtil.ok(channelVoList);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(o);
        resp.getWriter().println(s);
    }


    /**
     * 商品订单查询
     *
     * @param request  请求
     * @param response 响应
     */
    @GetMapping("/list")
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取页码参数参数
        String pageParma = request.getParameter("page");
        String limitParma = request.getParameter("limit");
        // 获取排序参数
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        // 获取查询参数
        String startParma = request.getParameter("start");
        String endParma = request.getParameter("end");
        String[] orderStatusArrayParma = request.getParameterValues("orderStatusArray");
        String userIdParma = request.getParameter("userId");
        String orderSn = request.getParameter("orderSn");
        // 完善性判定
        // 判定页码是否为数字 (多加一个userId)
        Integer page = null;
        Integer limit = null;
        Integer userId = null;
        try {
            page = Integer.parseInt(pageParma);
            limit = Integer.parseInt(limitParma);
            if (userIdParma != null) userId = Integer.parseInt(userIdParma);
        } catch (IllegalArgumentException e) {
            page = 1;
            limit = 20;
        }
        // 判定排序参数是否为空
        if (sort == null) sort = "add_time";
        if (order == null) order = "desc";
        // 将数据修改为日期格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        LocalDateTime start = null;
        LocalDateTime end = null;
        if (startParma != null && startParma.length() > 0) start = LocalDateTime.parse(startParma, dateTimeFormatter);
        if (endParma != null && endParma.length() > 0) end = LocalDateTime.parse(endParma, dateTimeFormatter);
        // 判定orderStatusArray参数
        List<Short> orderStatusArray = null;
        if (orderStatusArrayParma != null) {
            orderStatusArray = new ArrayList<>();
            for (String s : orderStatusArrayParma) {
                orderStatusArray.add(Short.parseShort(s));
            }
        }
        // 查询核心代码
        List<MarketOrder> marketOrders = adminOrderService.list(page, limit, sort, order, start, end, orderStatusArray, userId, orderSn);
        // TODO 结果判定

        // 响应报文
        Object ok = ResponseUtil.okList(marketOrders);
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 商品订单细节
     *
     * @param request  请求
     * @param response 响应
     */
    @GetMapping("/detail")
    private void detail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取id
        String idParam = request.getParameter("id");
        // 判定id是否为整数
        Integer id = null;
        try {
            id = Integer.parseInt(idParam);
        } catch (Exception e) {
            Object o = ResponseUtil.badArgument();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        // 订单细节核心代码
        Map<String, Object> map = adminOrderService.detail(id);
        // TODO 结果判定

        // 响应报文
        Object ok = ResponseUtil.ok(map);
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 修改商品订单
     *
     * @param request  请求
     * @param response 响应
     */
    @PostMapping("/ship")
    private void ship(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求体
        String requestBody = ZhouWenUtil.getRequestBody(request);
        // 获取请求参数
        Integer orderId = JacksonUtil.parseInteger(requestBody, "orderId");
        String shipChannel = JacksonUtil.parseString(requestBody, "shipChannel");
        Integer shipSn = JacksonUtil.parseInteger(requestBody, "shipSn");
        // TODO 判定参数

        // 获取对象
        MarketOrder marketOrder = JacksonUtil.getObjectMapper().readValue(requestBody, MarketOrder.class);
        // 修改订单的核心代码
        int flag = adminOrderService.ship(marketOrder);
        // 判定结果
        if (flag != 1) {
            Object o = ResponseUtil.updatedDataFailed();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        Object ok = ResponseUtil.ok();
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 退款修改商品订单
     *
     * @param request  请求
     * @param response 响应
     */
    @PostMapping("/refund")
    private void refund(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求体
        String requestBody = ZhouWenUtil.getRequestBody(request);
        // 获取对象
        MarketOrder marketOrder = JacksonUtil.getObjectMapper().readValue(requestBody, MarketOrder.class);
        // 修改订单的核心代码
        int flag = adminOrderService.refund(marketOrder);
        // 判定结果
        if (flag != 1) {
            Object o = ResponseUtil.updatedDataFailed();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        Object ok = ResponseUtil.ok();
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 订单删除
     *
     * @param request  请求
     * @param response 响应
     */
    @PostMapping("/delete")
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取Post请求体
        String requestBody = ZhouWenUtil.getRequestBody(request);
        // 数据转对象
        Integer orderId = JacksonUtil.parseInteger(requestBody, "orderId");
        // TODO 完善性判断

        // 删除订单的核心操作
        int flag = adminOrderService.delete(orderId);
        // 判定操作结果
        if (flag == 1) {
            // 响应
            Object ok = ResponseUtil.ok();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
        } else {
            // 响应
            Object o = ResponseUtil.updatedDataFailed();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
        }
    }
}